package cn.tedu.knows.sys.controller;


import cn.tedu.knows.commons.model.User;
import cn.tedu.knows.sys.service.IUserService;
import cn.tedu.knows.sys.vo.RegisterVO;
import cn.tedu.knows.sys.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-11-26
 */
@RestController
@RequestMapping("/v1/users")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/master")
    public List<User> teachers() {
        // 调用业务逻辑层方法返回所有讲师
        List<User> users = userService.getTeachers();
        return users;
    }

    @GetMapping("/me")
    public UserVO me(
            @AuthenticationPrincipal UserDetails user) {
        UserVO userVO = userService.getUserVO(user.getUsername());
        return userVO;
    }

    @PostMapping("/register")
    public String register(@Validated RegisterVO registerVO,
                           //专门接收前面验证的结果用的
                           //我们判断这个result是否有错误信息
                           BindingResult result) {
        //log 对象就是@Slf4j注解生效提供的,它能够记录日志
        log.debug("接收到表单信息:{}", registerVO);
        if (result.hasErrors()) {
            //获得验证结果中的错误信息(多条错误信息随机获取)
            String msg = result.getFieldError().getDefaultMessage();
            return msg;
        }
        userService.registerStudent(registerVO);
        return "ok";
    }
}
